<template>
  <el-form
    ref="formRef"
    :model="dynamicValidateForm"
    label-width="auto"
    class="demo-dynamic"
  >
    <el-form-item
      prop="name"
      label="典型工件名"
      :rules="[
        {
          required: true,
          message: 'Please input 典型工件名',
          trigger: 'blur',
        }
      ]"
    >
      <el-input v-model="dynamicValidateForm.name" />
    </el-form-item>

    
    <el-form-item
      prop="asm"
      label="是否是总成"
      :rules="[
        {
          required: true,
          message: '确认该工件是否是总成',
          trigger: 'blur',
        }
      ]"
      > <el-select v-model="dynamicValidateForm.asm.tag" placeholder="Select" style="width: 240px">
      <el-option
        v-for="item in [{key:'yes',value:true},{key:'false',value:false}]"
        :key="item.key"
        :label="item.key"
        :value="item.value"
      />
    </el-select>
      
       <!-- 为输入框单独设置验证规则 -->
    <el-form-item
      label="总成价值占比"
      v-if="dynamicValidateForm.asm.tag" 
      :rules="[
        { 
          required: true, 
          message: '请输入权重值', 
          trigger: 'blur' 
        },
        { 
          type: 'number', 
          message: '请输入整数', 
          trigger: 'blur' 
        },
        {
          validator: (rule, value, callback) => {
            if (value < 1 || value > 100) {
              callback(new Error('请输入1-100之间的整数'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }
      ]"
    style="margin-left: 10px;"
  >
        <el-input 
          v-model.number="dynamicValidateForm.asm.ratio" 
          placeholder="输入总成工序在总价值量中的占比"
          type="number"
          style="width: 300px;"
        />
      </el-form-item>
      
      
    </el-form-item>

    <el-form-item
      v-if="!dynamicValidateForm.asm.tag"
      prop="material"
      label="材料"
      :rules="[
        {
          required: true,
          message: 'Please input 材料',
          trigger: 'blur',
        }
      ]"
      > <el-select v-model="dynamicValidateForm.material._id" placeholder="Select" style="width: 240px">
      <el-option
        v-for="item in options"
        :key="item.name"
        :label="item.name"
        :value="item._id"
      />
    </el-select>
    </el-form-item>

    

    <el-form-item
      v-for="(step, index) in dynamicValidateForm.steps"
      :key="step._id"
      :label="'工序' + Number(index+1)"
      :prop="'steps.' + index + '._id'"
      :rules="{
        required: true,
        message: 'step can not be null',
        trigger: 'blur',
      }"
    >
      <el-select v-model="dynamicValidateForm.steps[index]._id" placeholder="Select" style="width: 240px">
        <el-option
          v-for="step in stepOptions"
          :key="step.name"
          :label="step.name"
          :value="step._id"
        />
      </el-select>
      <!-- <el-input v-model="dynamicValidateForm.steps[index].weighting" 
      placeholder="请输入1-100内的数字"
      type="number"
      style="width: 300px;"/> -->

      <!-- 为输入框单独设置验证规则 -->
    <el-form-item
    label="工序权重"
      :prop="'steps.'+ index + '.weighting'"
      :rules="[
        { 
          required: true, 
          message: '请输入权重值', 
          trigger: 'blur' 
        },
        { 
          type: 'number', 
          message: '请输入整数', 
          trigger: 'blur' 
        },
        {
          validator: (rule, value, callback) => {
            if (value < 1 || value > 100) {
              callback(new Error('请输入1-100之间的整数'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }
      ]"
    style="margin-left: 10px;"
  >
        <el-input 
          v-model.number="dynamicValidateForm.steps[index].weighting" 
          placeholder="请输入1-100内的数字"
          type="number"
          style="width: 300px;"
        />
      </el-form-item>

      <el-button class="mt-2" @click.prevent="removeDomain(step)">
        Delete
      </el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(formRef)">Submit</el-button>
      <el-button @click="addDomain">New domain</el-button>
      <el-button @click="resetForm(formRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'

import type { FormInstance } from 'element-plus'

const emit = defineEmits(['submit'])

const options = await $fetch("/api/material",{method:"GET"})
console.log(options);

const stepOptions = await $fetch("/api/step",{method:"GET"})
console.log(stepOptions);


const formRef = ref<FormInstance>()
const dynamicValidateForm = reactive<{
  steps: StepItem[]
  material: {
    _id:string
    name:string
    price :number
    recycle:number
  }
  asm:{
    tag:boolean
    ratio:number
  }
  name:string
  average:number
}>({
  steps: [{_id:'',
    name:'',
    price:0,
    weighting:0,
    equipment:''
  }],
  material : {
    _id: '',
    name:'',
    price :0,
    recycle :0
  },
  asm:{
    tag:false,
    ratio:0
  },
  name:'',
  average:0
})

// {
//     _id:1,
//     name:'方管',
//     material:{
//       name:'Q235',
//       price:5.4
//     },
//     average: 32,
//     steps: [
//       {
//         name:"车",
//         price:34,
//         weighting:15
//       },
//       {
//         name:"钻",
//         price:28,
//         weighting:65
//       },
//       {
//         name:"铣",
//         price:35,
//         weighting:20
//       },
//     ]
//   }

interface StepItem {
  _id:string
  name: string
  price: number
  weighting: number
  equipment: string
}


const removeDomain = (item: StepItem) => {
  const index = dynamicValidateForm.steps.indexOf(item)
  if (index !== -1) {
    dynamicValidateForm.steps.splice(index, 1)
  }
}

const addDomain = () => {
  dynamicValidateForm.steps.push({})
}

const checkWeighting = ()=>{
  let sum  = 0;
  let check = true;
  dynamicValidateForm.steps.forEach(step => {
    sum += step.weighting
  });
  if(sum!=100){
    check =  false
  }
  return check
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  
  if (!checkWeighting()) {
    alert('权重之和必须是100');
    return;
  } 

  formEl.validate(async (valid) => {
    if (valid) {
      console.log('submit!');
      await packData();
      console.log(dynamicValidateForm);
      
      // 验证成功后才执行 $fetch
      await $fetch('/api/commonpart', {
        method: 'POST',
        body: dynamicValidateForm
      });

      emit('submit')
    } else {
      alert('数据校验失败');
      return;
    }
  });
}

const packData = async () => {
  const materialRes = await $fetch(`/api/material/${dynamicValidateForm.material._id}`)
  console.log('material:',materialRes)
  dynamicValidateForm.material.name = materialRes.name;
  dynamicValidateForm.material.price = materialRes.price;
  dynamicValidateForm.material.recycle = materialRes.recycle;
  await Promise.all(dynamicValidateForm.steps.map(async (step)=>{
    const stepRes = await $fetch(`/api/step/${step._id}`,{method:'GET'})
    step.name = stepRes.name
    step.price = stepRes.price
    step.weighting = Number(step.weighting)
    step.equipment = stepRes.equipment
  }))
  let average = 0
  dynamicValidateForm.steps.forEach((step) =>{
    average += step.price* step.weighting/100
  })
  dynamicValidateForm.average = average
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
